﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _5._09设计一个自定义的awaitable类型
{
    class CustomAwaiter : INotifyCompletion
    {
        private string result = "Completed synchronously";
        private readonly bool completeSynchronously;

        public bool IsCompleted { get => completeSynchronously; }

        public CustomAwaiter(bool completeSynchronously)
        {
            this.completeSynchronously = completeSynchronously;
        }

        public string GetResult()
        {
            return result;
        }
        public void OnCompleted(Action continuation)
        {
            ThreadPool.QueueUserWorkItem(state =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                result = GetInfo();
                if (continuation != null) continuation();
            });
        }

        private string GetInfo()
        {
            return $"Thread is running on a thread id {Thread.CurrentThread.ManagedThreadId}, Is thread pool thread: {Thread.CurrentThread.IsThreadPoolThread}";
        }
    }
}
